package com.dragon.cloud.zconf.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.security.MessageDigest;

public class EncryptUtil {
    public static final String ENCODER_UTF8 = "UTF-8";
    public static final String ENCODER_ISO8859 = "ISO-8859-1";
    public static final String KEY_MAC = "HmacMD5";

    public static String encryptHMAC(String data, String key)
            throws Exception {
        String keyStr = URLDecoder.decode(key, ENCODER_UTF8);
        byte[] keyRaw = keyStr.getBytes(ENCODER_ISO8859);
        SecretKey secretKey = new SecretKeySpec(keyRaw, KEY_MAC);
        Mac mac = Mac.getInstance(KEY_MAC);
        mac.init(secretKey);
        byte[] raw = mac.doFinal(data.getBytes(ENCODER_UTF8));

        return hexOutputString(raw);
    }

    public static String hexOutputString(byte[] btInput) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            // 把密文转换成十六进制的字符串形式
            int j = btInput.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = btInput[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public final static String MD5(String input) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        try {
            byte[] btInput = input.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
